<?php
// 计划任务
class PlangoodsorderAction extends CommonAction {
	//魔术方法
	public function __construct(){
		parent::__construct();
	}
  public function index(){
  }
  
  private function write_log($msg = ''){
	  $log_path = './data/order_plan/'.date('Y').'/'.date('Y_m_d').'.log';
	  Log::write($msg, 'INFO', 3, $log_path);
  }
  
	//自动 确认收货 计划任务
	public function order_delivered_plan(){
		$where['pay_status'] = 2;// 支付状态；0，未付款；1，付款中 ；2，已付款
		$where['shipping_status'] = 1;//商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
		$where['order_status'] = 1;//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
		$where['is_upgrade'] = 0;
		$time=time()-24*3600*7;//发货后7天系统自动确认收货
		//小于 7天之前的 时间
		$where['shipping_time'] = array('elt',$time);//订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
		$pagesize = 10;
		$p = isset($_REQUEST['p']) && !empty($_REQUEST['p']) ? $_REQUEST['p'] : 1;

		// Log::write($p."确认收货计划任务开始：".date("Y-m-d H:i:s"), 'INFO', 3, $log_path);
		$this->write_log($p."确认收货计划任务开始：".date("Y-m-d H:i:s"));
		echo "确认收货计划任务开始：".date("Y-m-d H:i:s");

		$start = ($p - 1) * $pagesize;
		//$field = "order_id,order_sn,order_status,shipping_status,pay_status,goods_amount,order_amount,add_time";
		$field = "*";
		$order_model = M('g_order_info');
		$list = $order_model->where($where)->field($field)->limit($start, $pagesize)->order('shipping_time asc,order_id asc')->select();
		if($list){
			foreach ($list as $key => $value) {
				$this->order_delivered($value);
			}
			//sleep(秒)  usleep(毫秒)  让它睡上一会。
			sleep(2);
			$_REQUEST['p']=$p+1;
			$this->order_delivered_plan();
		}
		$this->write_log("确认收货计划任务END：".date("Y-m-d H:i:s"));
		echo "确认收货计划任务END：".date("Y-m-d H:i:s");
	}
	
	//确认收货
  public function order_delivered($data_info=array()){
      if(empty($data_info)){
        // Log::write("计划任务订单不存在：".date("Y-m-d  H:i:s"));
		$this->write_log("计划任务订单不存在：".date("Y-m-d H:i:s"));
        return false;
      }
      $order_show=$this->get_order_status($data_info);
      if($order_show['code']!='delivered'){//已发货
        // Log::write("计划任务订单状态错误：订单号：".$data_info['order_sn']."，".date("Y-m-d  H:i:s"));
		$this->write_log("计划任务订单状态错误：订单号：".$data_info['order_sn']."，".date("Y-m-d  H:i:s"));
        return false;
      }
      $refund=M('g_order_goods_refund')->where(array('member_id'=>$data_info['user_id'],'order_id'=>$data_info['order_id']))->find();
      if(!empty($refund) && $refund['refund_status']!='10'){//
        // Log::write("计划任务订单退货中 不可确认收货：订单号：".$data_info['order_sn']."，".date("Y-m-d  H:i:s"));
		$this->write_log("计划任务订单退货中 不可确认收货：订单号：".$data_info['order_sn']."，".date("Y-m-d  H:i:s"));
        return false;
      }
      $model_order = D('Mallorder');
      //查询商家信息
      $model_order->startTrans();
      $o_where["order_id"] =  array("eq",$data_info["order_id"]);
      //更改订单状态
      $data = array();
      $data['shipping_status']  = 2;
      $data['finnshed_time']  = time();
      $order_res = $model_order->editOrder($data,$o_where);
            //记录商家日志
      if($order_res!==false){
        //记录订单日志
        $data = array();
        $data['order_id'] = $data_info['order_id'];
        $data['log_role'] = 'system';//系统
        $data['log_msg'] = '系统自动确认收货';
        $data['log_orderstate'] = '40';
        $insert = $model_order->addOrderLog($data);

        ///用户返利 返积分 认证等
        $ress = $this->set_member_exchange($data_info);///用户 返利等操作
		if(isset($ress['status']) && $ress['status']){
			// Log::write("计划任务订单自动确认收货分配利润成功，订单号：".$data_info['order_sn']);
			$this->write_log("计划任务订单自动确认收货分配利润成功，订单号：".$data_info['order_sn']);
		}else{
			// Log::write("计划任务订单自动确认收货分配利润错误，订单号：".$data_info['order_sn'].'('.$ress['msg'].')');
			$this->write_log("计划任务订单自动确认收货分配利润错误，订单号：".$data_info['order_sn'].'('.$ress['msg'].')');
		}
		
        $model_order->commit();
        echo "计划任务订单自动确认收货成功：订单号：".$data_info['order_sn']."，".date("Y-m-d  H:i:s").'<br/>';
        // Log::write("计划任务订单自动确认收货成功：订单号：".$data_info['order_sn']."，".date("Y-m-d  H:i:s"));
		
		$this->write_log("计划任务订单自动确认收货成功：订单号：".$data_info['order_sn']."，".date("Y-m-d  H:i:s"));
        return true;
      }else{
        // Log::write("计划任务订单自动确认收货失败：订单号：".$data_info['order_sn']."，".date("Y-m-d  H:i:s"));
		$this->write_log("计划任务订单自动确认收货失败：订单号：".$data_info['order_sn']."，".date("Y-m-d  H:i:s"));
        return false;
      }
  }


    /*
	*
	* 利润分配
	* $data_info array：订单信息，必须包括order_id , int：order_id;
	* 返回 status 0错误（msg）为错误信息 1成功
	* kkxx 2016-10-08 
	*/
    private function set_member_exchange($data_info = array()){
		$ret = array();
		$ret['status'] = 0;
		
		if(is_array($data_info)){
			$order_id = $data_info['order_id'];
		}else{
			$order_id = $data_info;
		}
		if(!$order_id){
			$ret['msg'] = '参数错误！';
            return $ret;
		}
		$g_order_info = M('g_order_info');
		// $order_info = $g_order_info->where(array('order_id'=>409))->find();
		$order_info = $g_order_info->where(array('order_id'=>$order_id))->find();
        if (empty($order_info)){
			$ret['msg'] = '没有找到订单';
            return $ret;
        }
		
		if($order_info['pay_status'] != 2){
			$ret['msg'] = '订单没有付款';
            return $ret;
		}
		
		$pre = C('DB_PREFIX');//表前缀
		
        //用户自己返利  用户积分增加  返利日志 积分增加日志
		$field = 'mem.id, mem.member_card, mem.mobile, mem.recommend_code, mem.indirect_recommend_code, mem.indirect2_recommend_code, mem.member_status, mem.member_vip_type, mem.member_vip_order, md.provinceid, md.cityid, md.areaid, md.relevel, md.repath';
        $member_info = M()->table($pre . 'member mem')
		->join($pre . 'member_detail md on mem.id=md.member_id')
		->where(array('mem.id' => $order_info['user_id']))
		->field($field)->find();
		
		//shop_rebate_status  123 级返利状态 1 返利  0不返
        $shop_rebate_status = 0;//返利类型 1分享返利 0正常返利(123级返利) 2升级返利
        $member_tuijian_data = array();//返利记录
		
        $order_save_data = array();//订单返利 数据
        $order_save_data['profit_type'] = 0;//返利类型 1分享返利 0正常返利(123级返利)
        $order_save_data['order_profit'] = $order_info['order_amount'];//订单利润= 应付款金额-订单返利
        $order_save_data['order_rebate'] = 0;//订单返利金额
		
		//订单利润
		$is_income = TRUE;
		$money = 0; $c_money = 0; $syb_money = 0;
		if($order_info['is_upgrade'] == 1){
			$level_order = M('member_level_order')->where(array('id'=>$order_info['order_sn']))->find();
			if($level_order['last_level'] > 0){
				$is_income = FALSE;
			}
			$shop_rebate_status = 2;
			$money = $order_info['goods_amount'];
			$syb_money = $order_info['goods_amount'];
		}else{
			$order_goods_info=M('g_order_goods')->where('order_id='.$order_info['order_id'])->select();
			foreach ($order_goods_info as $k=>$v){
				$goods_id=$v['goods_id'];
				$goods_number=$v['goods_number'];
				$goods_price=$v['goods_price'];
				$purchase_price=M('g_goods')->where("goods_id=$goods_id")->getField('purchase_price');
				$money += (($goods_price-$purchase_price)*$goods_number);
			}
			
			$c_money = $money;
		}
		
		if($money <= 0){
			$ret['msg'] = '利润金额错误（'.$money.'）';
			return $ret;
		}
		
		$money_integral = 10;
		//分配比例
		if($order_info['is_upgrade']==1){
			$rem1_money_ratio = 0.28;
			$rem1_integral_ratio = 0.05;
			$rem2_money_ratio = 0.04;
			$rem2_integral_ratio = 0.02;
			$rem3_money_ratio = 0.03;
			$rem3_integral_ratio = 0.01;
		}else{
			$rem1_money_ratio = 0.3;
			$rem1_integral_ratio = 0.1;
			$rem2_money_ratio = 0.08;
			$rem2_integral_ratio = 0.02;
			$rem3_money_ratio = 0.03;
			$rem3_integral_ratio = 0.02;
		}
		$total_ratio = $rem1_money_ratio + $rem1_integral_ratio + $rem2_money_ratio + $rem3_money_ratio + $rem3_integral_ratio;
		
		//推荐人查找
		if($order_info['is_upgrade'] == 0 && $order_info['share_uid'] > 0){ //如果用户的订单推荐人不是原推荐人，利润分配使用订单推荐人的分配路线
			$share_member = M('member')->where(array('id'=>$order_info['share_uid']))->find();
			$share_member_detail = M('member_detail')->where(array('member_id'=>$order_info['share_uid']))->find();
			if(isset($share_member['member_card']) && isset($share_member_detail['repath']) && $share_member['member_card'] != $member_info['recommend_code']){
				$member_info['repath'] = $share_member_detail['repath'].','.$member_info['id'];
				$member_info['relevel'] = $share_member_detail['relevel'] + 1;
			}
		}
		
		$repath = explode(',', $member_info['repath']);
		$member_list_array = M('member')->where(array('id' => array('in', $member_info['repath'])))->select();
		$member_list = array();
		foreach($member_list_array as $item){
			$member_list[$item['id']] = $item;
		}
		
		$i = 0;
		$num = 0;
		$member1_info = $member2_info = $member3_info = '';
		$recommend_member_info = array();
		while($i < $member_info['relevel']){
			$uid = array_pop($repath);
			if($uid != $member_info['id'] || $member_info['id'] == $order_info['share_uid']){
				$num ++;
				$recommend_member_info[$num] = $member_list[$uid];
			}
			$i++;
		}
		
		$member1_info = isset($recommend_member_info[1]) ? $recommend_member_info[1] : '';
		$member2_info = isset($recommend_member_info[2]) ? $recommend_member_info[2] : '';
		$member3_info = isset($recommend_member_info[3]) ? $recommend_member_info[3] : '';
		
		$left_money = $money;
		
		//直接推荐人
		if($is_income && $member1_info && $member1_info['mobile'] && $member1_info['member_vip_type']){
			$member1_money = mb_number($money * $rem1_money_ratio);
			$member1_integral_money = mb_number($money * $rem1_integral_ratio);
			$member1_integral = $member1_integral_money * $money_integral;
			
			if($member1_money > 0 || $member1_integral > 0){
				$order_save_data['order_rebate'] += ($member1_money + $member1_integral_money);
				
				$log = array();
				$log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
				$log['type5_type']=1;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
				$log['order_id'] = $order_info['order_id'];
				$log['des'] = '直接推荐人('.$member_info['member_card'].')消费收益：￥' . $member1_money;
				
				//金额日志
				$this->set_member_balance($member1_info['id'], 1, $member1_money, $log);
				//积分日志
				$log['des'] = '直接推荐人('.$member_info['member_card'].')消费积分：' . $member1_integral;
				$this->set_member_points($member1_info['id'], 1, ($member1_integral), $log);
				
				//收益记录
				$tuijian_data = array();
				$tuijian_data['member_id'] = $member1_info['id'];
				$tuijian_data['order_id'] = $order_info['order_id'];
				$tuijian_data['type'] = 2;
				$tuijian_data['money'] = $member1_money;
				$tuijian_data['integral'] = $member1_integral;
				$tuijian_data['des'] = '直接推荐人('.$member_info['member_card'].')消费收益：￥' . $member1_money . '，消费积分：' . $member1_integral;
				$member_tuijian_data[] = $tuijian_data;
			}
		}
		
		//间接推荐人
		if($is_income && $member2_info && $member2_info['mobile'] && $member2_info['member_vip_type']){
			$member2_money = mb_number($money * $rem2_money_ratio);
			$member2_integral_money = mb_number($money * $rem2_integral_ratio);
			$member2_integral = $member2_integral_money * $money_integral;
			
			if($member2_money > 0 || $member2_integral > 0){
				$order_save_data['order_rebate'] += ($member2_money + $member2_integral_money);
				
				$log = array();
				$log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
				$log['type5_type'] = 2;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
				$log['order_id'] = $order_info['order_id'];
				$log['des'] = '间接推荐人('.$member_info['member_card'].')消费收益：￥' . $member2_money;
				
				//金额日志
				$this->set_member_balance($member2_info['id'], 1, $member2_money, $log);
				//积分日志
				$log['des'] = '间接推荐人('.$member_info['member_card'].')消费积分：' . $member2_integral;
				$this->set_member_points($member2_info['id'], 1, ($member2_integral), $log);
				
				//收益记录
				$tuijian_data = array();
				$tuijian_data['member_id'] = $member2_info['id'];
				$tuijian_data['order_id'] = $order_info['order_id'];
				$tuijian_data['type'] = 3;
				$tuijian_data['money'] = $member2_money;
				$tuijian_data['integral'] = $member2_integral;
				$tuijian_data['des'] = '间接推荐人('.$member_info['member_card'].')消费收益：￥' . $member2_money . '，消费积分：' . $member2_integral;
				$member_tuijian_data[] = $tuijian_data;
			}
		}
		
		//间接二级推荐人
		if($is_income && $member3_info && $member3_info['mobile'] && $member3_info['member_vip_type']){
			$member3_money = mb_number($money * $rem3_money_ratio);
			$member3_integral_money = mb_number($money * $rem3_integral_ratio);
			$member3_integral = $member3_integral_money * $money_integral;
			
			if($member3_money > 0 || $member3_integral > 0){
				$order_save_data['order_rebate'] += ($member3_money + $member3_integral_money);
				
				$log = array();
				$log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
				$log['type5_type'] = 3;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
				$log['order_id'] = $order_info['order_id'];
				$log['des'] = '间接二级推荐人('.$member_info['member_card'].')消费收益：￥' . $member3_money;
				
				//金额日志
				$this->set_member_balance($member3_info['id'], 1, $member3_money, $log);
				//积分日志
				$log['des'] = '间接二级推荐人('.$member_info['member_card'].')消费积分：' . $member3_integral;
				$this->set_member_points($member3_info['id'], 1, ($member3_integral), $log);
				
				//收益记录
				$tuijian_data = array();
				$tuijian_data['member_id'] = $member3_info['id'];
				$tuijian_data['order_id'] = $order_info['order_id'];
				$tuijian_data['type'] = 5;
				$tuijian_data['money'] = $member3_money;
				$tuijian_data['integral'] = $member3_integral;
				$tuijian_data['des'] = '间接二级推荐人('.$member_info['member_card'].')消费收益：￥' . $member3_money . '，消费积分：' . $member3_integral;
				$member_tuijian_data[] = $tuijian_data;
			}
		}
		
		$order_save_data['profit_type'] = $shop_rebate_status;
		$order_save_data['order_profit_all'] = $total_ratio * $money;
		//订单利润 order_profit
		//订单返利金额 order_rebate
		//订单返利总金额 返利池 order_profit_all
		$order_save_data['order_profit'] = $order_save_data['order_profit'] - $order_save_data['order_rebate'];
		M('g_order_info')->where(array('order_id' => $order_info['order_id']))->save($order_save_data);


		if (empty($shop_rebate_status)) {
			$order_goods = M('g_order_goods')->where(array('order_id' => $data_info["order_id"]))->select();
			$member_model = M('member');
			$goods_model = M("g_goods");
			if ($order_goods) {
				foreach ($order_goods as $key => $value) {
					//增加销量
					$goods_model->where(array("goods_id" => $value['goods_id']))->setInc("goods_salesvolume", $value['goods_number']);
				}
			}
		}


		//累计业绩
		if($member_info['member_vip_type'] > 0 && $order_info['is_upgrade'] == 0){
			$yeji_user_ids = $member_info['repath'];
		}else{
			$index_num = strrpos($member_info['repath'], ',');
			$yeji_user_ids = substr($member_info['repath'], 0, $index_num);
		}
		if($syb_money > 0){ //累计创业业绩
			M('member_detail')->where(array('member_id'=>array('in', $yeji_user_ids)))->setInc('syb_yeji', $syb_money);
		}
		if($c_money > 0){ //累计消费业绩
			M('member_detail')->where(array('member_id'=>array('in', $yeji_user_ids)))->setInc('c_yeji', $c_money);
		}
		
		if(!empty($member_tuijian_data)) { //写入收益记录
			$rebate_record_model = M('rebate_record');
			$time = time();
			foreach ($member_tuijian_data as $key => $value) {
				$value['add_time'] = $time;
				$value['status'] = 1;//状态 1用户收益 2 商家返利
				$rebate_record_model->add($value);
			}
		}
		
		$ret['status'] = 1;
		return $ret;
	}

    //获取订单状态
  public function get_order_status($order_info=array()){
      if(empty($order_info)){
        return array();
      }
// pay_status支付状态；0，未付款；1，付款中 ；2，已付款
// shipping_status 商品配送情况，0，未发货； 1，已发货；2，已收货；3，备货中
//order_status订单状态。0，未确认；1，已确 认；2，已取消；3，无效；4，退货；
      $order_status=array('0'=>'未确认','1'=>'已确认','2'=>'已取消','3'=>'无效','4'=>'已退货');
      $shipping_status=array('0'=>'未发货','1'=>'已发货','2'=>'已完成','3'=>'备货中');
      $code=$name="";
      if($order_info['order_status']==1){//已确认
        switch ($order_info['shipping_status']) {
          case '1':
            $code="delivered";//已发货
            break;
          case '2':
            $code="received";//已收货
            break;
          default:
            $code='nondelivery';//未发货
            break;
        }
        return array('code'=>$code,'name'=>$shipping_status[$order_info['shipping_status']]);
      }else{//未确认 
           //2已取消；3无效；4，退货；
          if(in_array($order_info['order_status'], array('2','3','4'))){
                return array('code'=>'finish','name'=>$order_status[$order_info['order_status']]);
          }else{////未确认
            if($order_info['pay_status']==2){//已付款 待确认
                    return array('code'=>'unconfirmed','name'=>'待确认');
            }else{
                    return array('code'=>'nopay','name'=>'未付款');
            }
          }
      }
      
  }



}